<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            :icon="Plus"
            size="mini"
            @click="handleAdd()"
            v-hasPermi="['kjy:application:add']"
        >新增奖项</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            :icon="Delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:application:remove']"
        >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
        size="large"
        :header-row-style="{ height: '70px', color: 'black', 'font-size': '16px' }"
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :row-style="{'height': '60px'}"
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="证书类别" align="center" prop="qualificationCategory" />
      <el-table-column label="奖项名称" align="center" prop="name" />
      <el-table-column label="证书附件" align="partner" prop="certificateFile">
        <template #default="scope">
          <a
              v-if="scope.row.certificateFile !== null"
              :href="getFirstItem(scope.row.certificateFile)"
              target="_blank"
          >{{ getFirstItem(scope.row.certificateFile).split('/').pop() }}</a
          >
        </template>
      </el-table-column>
      <el-table-column label="获奖时间" align="center" prop="awardDate"> </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="info">未审核</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">审核成功</el-tag>
          <el-tag v-if="scope.row.status === 2" type="danger">审核失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="primary" :icon="Edit" link v-if="scope.row.status === 0" @click="handleUpdate(scope.row)"
          >修改</el-button
          >
          <el-button size="mini" type="danger" :icon="Delete" link v-if="scope.row.status === 0" @click="handleDelete(scope.row)"
          >删除</el-button
          >
          <el-button size="mini" type="info" :icon="View" link v-if="scope.row.status === 1 || scope.row.status === 2" @click="handleView(scope.row)"
          >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div
        :style="{
        padding: '15px',
        'background-color': '#fff',
        display: 'flex',
        'justify-content': 'end',
      }"
    >
      <el-pagination
          background
          :total="total"
          layout="prev, pager, next"
          v-model:page-size="queryParams.size"
          v-model:current-page="queryParams.current"
          @current-change="getList"
      />
    </div>

    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="颁发部门或机构" prop="enterpriseName">
          <el-input
              v-model="form.enterpriseName"
              placeholder="请输入颁发部门或机构"
              clearable
              :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="证书类别" prop="qualificationCategory">
          <el-select v-model="form.qualificationCategory" placeholder="请选择证书类别" clearable>
            <el-option
                v-for="(item, index) in qualificationcategoryOptions"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictLabel"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="奖项名称" prop="name">
          <el-input
              v-model="form.name"
              placeholder="请输入奖项名称"
              clearable
              :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="获奖日期" prop="awardDate">
          <el-date-picker
              v-model="form.awardDate"
              type="date"
              placeholder="请选择获奖日期"
              clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="证书附件" prop="certificateFile">
          <el-upload
              :headers="headers"
              multiple
              :accept="['doc', 'docx', 'pdf', 'png', 'jpg', 'jpeg']"
              :on-success="HandleSuccess"
              action="api/file/upload"
              :limit="3"
              :file-list="FileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不超过5mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  :disabled="isView" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getAwardListByEnterpriseId,
  getAwardType,
  addInfo,
  updateInfo,
  delInfo,
} from '@/api/my-award';
import { getToken } from '@/utils/storage';
import { Delete, Plus, Edit, View } from '@element-plus/icons-vue';
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);
const headers = ref({
  Authorization: getToken(),
});
const queryParams = reactive({
  current: 1,
  size: 10,
  enterpriseName: null,
});
const form = ref({
  id: null,
  enterpriseName: '',
  qualificationCategory: '',
  name: '',
  certificateFile: '',
  awardDate: '',
  publishTime: '',
  status: 0, // 添加状态字段，默认为0（未审核）
});
const FileList = ref([]);
const rules = ref({
  enterpriseName: [{ required: true, message: '颁发部门或机构不能为空', trigger: 'blur' }],
  qualificationCategory: [
    { required: true, message: '证书类别不能为空', trigger: 'blur' },
  ],
  name: [{ required: true, message: '奖项名称不能为空', trigger: 'blur' }],
  awardDate: [{ required: true, message: '获奖时间不能为空', trigger: 'blur' }],
});
const tableData = ref([]);
const qualificationcategoryOptions = ref([]);
const selectedItem = ref(null);
const searchText = ref(null);
const isLoading = ref(false);
const isView = ref(false);
const getList = async () => {
  loading.value = true;
  try {
    const response = await getAwardListByEnterpriseId(queryParams);
    tableData.value = response.data.records;
    total.value = response.data.total;
    queryParams.current = response.data.current;
  } finally {
    loading.value = false;
  }
};

const HandleSuccess = (response) => {
  form.value.certificateFile = response.data.url;
};
const getFirstItem = (item) => {
  if (item !== null && typeof item === 'string') {
    const items = item.split(',');
    return items.length > 0 ? items[0].trim() : item;
  }
  return item;
};

const cancel = () => {
  open.value = false;
  resetForm();
};

const resetForm = () => {
  form.value = {
    id: null,
    enterpriseName: '',
    qualificationCategory: undefined,
    name: undefined,
    certificateFile: null,
    level: 0,
    awardDate: '',
    publishTime: '',
    status: 0, // 重置状态字段
  };
  FileList.value = [];
  selectedItem.value = null;
  searchText.value = null;
};

const handleQuery = () => {
  getList();
};

const resetQuery = () => {
  resetForm();
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  resetForm();
  open.value = true;
  title.value = '添加奖项';
  isView.value = false; // 设置为添加模式
};

const handleUpdate = (row) => {
  resetForm();
  form.value = { ...row }; // 使用扩展运算符创建副本
  FileList.value = row.certificateFile ? [{ name: row.certificateFile, url: row.certificateFile }] : [];
  open.value = true;
  title.value = '修改奖项';
};

const handleView = (row) => {
  resetForm();
  form.value = { ...row }; // 使用扩展运算符创建副本
  FileList.value = row.certificateFile ? [{ name: row.certificateFile, url: row.certificateFile }] : [];
  open.value = true;
  title.value = '查看奖项';
  isView.value = true; // 设置为查看模式
};

const submitForm = () => {
  console.log(form.value);
  const isValid = validateForm();
  if (isValid) {
    form.value.publishTime = new Date().toISOString();
    if (form.value.id != null) {
      updateInfo(form.value)
          .then((res) => {
            if (res.code === 200) {
              ElMessage.success('修改成功');
            } else {
              ElMessage.error(res.msg);
            }
            open.value = false;
            getList();
          })
          .catch((error) => console.error('更新失败:', error));
    } else {
      addInfo(form.value)
          .then((res) => {
            if (res.code === 200) {
              ElMessage.success('添加成功');
            } else {
              ElMessage.error(res.msg);
            }
            open.value = false;
            getList();
          })
          .catch((error) => console.error('添加失败:', error));
    }
  }
};

const validateForm = () => {
  // 检查必填字段是否已填写
  if (!form.value.enterpriseName) {
    ElMessage.error('颁发部门或机构不能为空');
    return false;
  }
  if (!form.value.qualificationCategory) {
    ElMessage.error('证书类别不能为空');
    return false;
  }
  if (!form.value.name) {
    ElMessage.error('奖项名称不能为空');
    return false;
  }
  if (!form.value.awardDate) {
    ElMessage.error('获奖时间不能为空');
    return false;
  }
  return true;
};

const handleDelete = (row) => {
  const idsToDelete = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除选中数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        delInfo(idsToDelete)
            .then(() => {
              getList();
              ElMessage.success('删除成功');
            })
            .catch((error) => console.error('删除失败:', error));
      })
      .catch(() => {});
};

onMounted(() => {
  getList();
  getAwardType().then((response) => {
    qualificationcategoryOptions.value = response.data;
  });
});

watch(
    queryParams,
    () => {
      handleQuery();
    },
    { deep: true }
);
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  width: 100%;
  background-color: #fff;
}
</style>